﻿using FasterBuild;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;

namespace FileSynchronization
{
    public class DataAccess : ControllerBase
    {
        public ILog _logger;
        public SqlSugarScopeProvider Db => GetSqlSugarClient("Db");

        private SqlSugarScope dbScope;
        public DataAccess()
        {
            _logger = ServiceProviderStatic.GetService<ILog>();
            InitDb();
        }

        private SqlSugarScopeProvider GetSqlSugarClient(string dbKey)
        {
            if (dbScope is null) InitDb();

            return dbScope.GetConnectionScope(dbKey);
        }

        private void InitDb()
        {
            List<ConnectionConfig> connList = new List<ConnectionConfig>();
#if DEBUG
            var settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Setting/DBSettingDebugger.json");
#else
            var settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Setting/DBSetting.json");
#endif
            if (System.IO.File.Exists(settingPath))
            {
                var jsonString = System.IO.File.ReadAllText(settingPath);
                try
                {
                    var dbSettings = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
                    foreach (var db in dbSettings)
                    {
                        connList.Add(new ConnectionConfig()
                        {
                            ConfigId = db.Key,
                            DbType = DbType.MySql,
                            ConnectionString = db.Value,
                            IsAutoCloseConnection = true
                        });
                    }
                    dbScope = new SqlSugarScope(connList, db =>
                    {
                        foreach (var ds in dbSettings)
                        {
                            db.GetConnectionScope(ds.Key).Aop.OnLogExecuted = (sql, p) =>//执行SQL 结束后
                            {
                                Console.WriteLine(sql);
                            };

                            db.GetConnectionScope(ds.Key).Aop.OnError = (sql) =>//执行SQL 错误事件
                            {
                                Console.WriteLine(sql);
                            };
                        }
                    });
                }
                catch { }
            }
        }

        private class Error
        {
            public int _Size { get; set; }

            public string IsRefCursor { get; set; }

            public int DbType { get; set; }

            public int Direction { get; set; }

            public string IsNullable { get; set; }

            public string ParameterName { get; set; }

            public int Size { get; set; }

            public string SourceColumn { get; set; }

            public string SourceColumnNullMapping { get; set; }

            public string UdtTypeName { get; set; }

            public string Value { get; set; }

            public string TempDate { get; set; }

            public int SourceVersion { get; set; }

            public string TypeName { get; set; }

            public int Precision { get; set; }

            public int Scale { get; set; }
        }
    }

    public static class DbExtensions
    {
        public static async Task<long> SaveEntityInfo<T>(this SqlSugarScopeProvider db, T entity) where T : class, new()
        {
            var id = long.Parse(entity.GetType().GetProperty("ID").GetValue(entity, null).ToString());

            if (id == 0)
                return await db.Insertable(entity).ExecuteReturnBigIdentityAsync();
            else
            {
                await db.Updateable(entity).ExecuteCommandAsync();
                return id;
            }
        }
    }
}
